/**
 * 小程序兼容性处理
 * 解决各种第三方库在小程序环境中的兼容性问题
 */

// 检查当前运行环境
export const getEnv = () => {
  if (typeof wx !== 'undefined') return 'weapp'
  if (typeof my !== 'undefined') return 'alipay'
  if (typeof swan !== 'undefined') return 'swan'
  if (typeof tt !== 'undefined') return 'tt'
  if (typeof window !== 'undefined') return 'h5'
  return 'unknown'
}

// 是否为小程序环境
export const isMiniProgram = () => {
  const env = getEnv()
  return ['weapp', 'alipay', 'swan', 'tt'].includes(env)
}

// Lottie 兼容性处理
export const initLottieCompat = () => {
  if (!isMiniProgram()) return

  // 拦截动态创建 canvas 的操作
  if (typeof document !== 'undefined') {
    const originalCreateElement = document.createElement
    
    document.createElement = function(tagName, options) {
      if (tagName && tagName.toLowerCase() === 'canvas') {
        console.warn('[兼容性处理] 拦截了动态创建 canvas 的操作')
        
        // 返回一个模拟的 canvas 对象
        const mockCanvas = {
          tagName: 'CANVAS',
          nodeName: 'CANVAS',
          width: 300,
          height: 150,
          style: {},
          classList: {
            add: () => {},
            remove: () => {},
            contains: () => false
          },
          getContext: (type) => {
            console.warn(`[兼容性处理] 模拟 canvas.getContext('${type}')`)
            return createMockContext(type)
          },
          addEventListener: () => {},
          removeEventListener: () => {},
          setAttribute: () => {},
          getAttribute: () => null,
          appendChild: () => {},
          removeChild: () => {},
          getBoundingClientRect: () => ({
            left: 0, top: 0, right: 300, bottom: 150,
            width: 300, height: 150, x: 0, y: 0
          })
        }
        
        return mockCanvas
      }
      
      // 其他元素正常创建
      if (originalCreateElement) {
        return originalCreateElement.call(this, tagName, options)
      }
      
      // 如果原方法不存在，返回一个基本的模拟对象
      return {
        tagName: tagName.toUpperCase(),
        style: {},
        setAttribute: () => {},
        getAttribute: () => null,
        appendChild: () => {},
        removeChild: () => {}
      }
    }
  }

  // 处理可能的 Lottie 全局对象
  if (typeof window !== 'undefined') {
    // 监听 lottie 对象的创建
    let lottieCheckInterval = setInterval(() => {
      if (window.lottie) {
        console.log('[兼容性处理] 检测到 Lottie 对象，进行兼容性处理')
        patchLottie(window.lottie)
        clearInterval(lottieCheckInterval)
      }
    }, 100)
    
    // 10秒后停止检查
    setTimeout(() => {
      clearInterval(lottieCheckInterval)
    }, 10000)
  }
}

// 创建模拟的 canvas context
const createMockContext = (type) => {
  const mockMethods = {
    // 2D context 方法
    clearRect: () => {},
    fillRect: () => {},
    strokeRect: () => {},
    beginPath: () => {},
    closePath: () => {},
    moveTo: () => {},
    lineTo: () => {},
    arc: () => {},
    arcTo: () => {},
    bezierCurveTo: () => {},
    quadraticCurveTo: () => {},
    fill: () => {},
    stroke: () => {},
    clip: () => {},
    save: () => {},
    restore: () => {},
    translate: () => {},
    rotate: () => {},
    scale: () => {},
    transform: () => {},
    setTransform: () => {},
    drawImage: () => {},
    createImageData: () => ({ data: new Uint8ClampedArray(4), width: 1, height: 1 }),
    getImageData: () => ({ data: new Uint8ClampedArray(4), width: 1, height: 1 }),
    putImageData: () => {},
    measureText: (text) => ({ width: text.length * 8 }),
    
    // WebGL context 方法
    getParameter: () => null,
    getExtension: () => null,
    createShader: () => null,
    createProgram: () => null,
    useProgram: () => {},
    attachShader: () => {},
    linkProgram: () => {},
    getProgramParameter: () => true,
    getShaderParameter: () => true,
    createBuffer: () => null,
    bindBuffer: () => {},
    bufferData: () => {},
    enableVertexAttribArray: () => {},
    vertexAttribPointer: () => {},
    drawArrays: () => {},
    drawElements: () => {},
    
    // 通用属性
    canvas: null,
    fillStyle: '#000000',
    strokeStyle: '#000000',
    lineWidth: 1,
    font: '10px sans-serif',
    textAlign: 'start',
    textBaseline: 'alphabetic'
  }
  
  return new Proxy(mockMethods, {
    get(target, prop) {
      if (prop in target) {
        return target[prop]
      }
      // 对于未定义的方法，返回空函数
      return () => {}
    },
    set(target, prop, value) {
      target[prop] = value
      return true
    }
  })
}

// 修补 Lottie 对象
const patchLottie = (lottie) => {
  if (!lottie.loadAnimation) return
  
  const originalLoadAnimation = lottie.loadAnimation
  
  lottie.loadAnimation = function(params) {
    console.warn('[兼容性处理] Lottie 动画加载被拦截')
    
    if (!params) {
      console.error('[兼容性处理] Lottie 参数为空')
      return createMockAnimation()
    }
    
    // 强制使用 SVG 渲染器
    const safeParams = {
      ...params,
      renderer: 'svg',
      rendererSettings: {
        ...params.rendererSettings,
        preserveAspectRatio: 'xMidYMid slice',
        progressiveLoad: false,
        hideOnTransparent: true
      }
    }
    
    // 如果没有容器，创建一个虚拟容器
    if (!safeParams.container) {
      safeParams.container = document.createElement('div')
    }
    
    try {
      return originalLoadAnimation.call(this, safeParams)
    } catch (error) {
      console.error('[兼容性处理] Lottie 动画加载失败:', error)
      return createMockAnimation()
    }
  }
}

// 创建模拟的动画对象
const createMockAnimation = () => {
  return {
    play: () => console.log('[模拟] 动画播放'),
    pause: () => console.log('[模拟] 动画暂停'),
    stop: () => console.log('[模拟] 动画停止'),
    destroy: () => console.log('[模拟] 动画销毁'),
    setSpeed: (speed) => console.log(`[模拟] 设置动画速度: ${speed}`),
    setDirection: (direction) => console.log(`[模拟] 设置动画方向: ${direction}`),
    goToAndStop: (frame) => console.log(`[模拟] 跳转到帧: ${frame}`),
    goToAndPlay: (frame) => console.log(`[模拟] 跳转并播放: ${frame}`),
    addEventListener: () => {},
    removeEventListener: () => {},
    totalFrames: 0,
    currentFrame: 0,
    isPaused: true,
    isLoaded: true
  }
}

// 初始化所有兼容性处理
export const initMiniProgramCompat = () => {
  const env = getEnv()
  console.log(`[兼容性处理] 当前环境: ${env}`)
  
  if (isMiniProgram()) {
    console.log('[兼容性处理] 初始化小程序兼容性处理')
    initLottieCompat()
    
    // 可以在这里添加其他兼容性处理
    initOtherCompat()
  }
}

// 其他兼容性处理
const initOtherCompat = () => {
  // 处理可能的 DOM 操作兼容性问题
  if (typeof window !== 'undefined' && !window.requestAnimationFrame) {
    window.requestAnimationFrame = (callback) => {
      return setTimeout(callback, 16)
    }
    window.cancelAnimationFrame = (id) => {
      clearTimeout(id)
    }
  }
  
  // 处理可能的 console 兼容性问题
  if (typeof console === 'undefined') {
    window.console = {
      log: () => {},
      warn: () => {},
      error: () => {},
      info: () => {},
      debug: () => {}
    }
  }
}

export default {
  getEnv,
  isMiniProgram,
  initMiniProgramCompat,
  initLottieCompat
}